﻿//PlazaSettings.xaml.cs
//Copyright (c) 2013 StockSharp LLC, all rights reserved.
//This code module is part of StockSharp library.
//This code is licensed under the GNU GENERAL PUBLIC LICENSE Version 3.
//See the file License.txt for the license details.
//More info on: http://stocksharp.com

namespace StockSharp.Plaza.Xaml
{
	using System.Linq;
	using System.Net;

	using Ecng.Collections;
	using Ecng.Common;

	using StockSharp.BusinessEntities;
	using StockSharp.Plaza;
	using StockSharp.Xaml;

	/// <summary>
	/// Визуальная панель настроек <see cref="PlazaTrader"/>.
	/// </summary>
	public partial class PlazaSettings : ITraderSettingsPanel
	{
		/// <summary>
		/// Создать <see cref="PlazaSettings"/>.
		/// </summary>
		public PlazaSettings()
		{
			InitializeComponent();
		}

		/// <summary>
		/// <see cref="PlazaTrader.Login"/>.
		/// </summary>
		public string Login
		{
			get { return LoginCtrl.Text; }
			set
			{
				LoginCtrl.Text = value;

				if (!value.IsEmpty())
					IsAutorization = true;
			}
		}

		/// <summary>
		/// <see cref="PlazaTrader.Password"/>.
		/// </summary>
		public string Password
		{
			get { return PasswordCtrl.Password; }
			set
			{
				PasswordCtrl.Password = value;

				if (!value.IsEmpty())
					IsAutorization = true;
			}
		}

		/// <summary>
		/// <see cref="PlazaTrader.AppName"/>.
		/// </summary>
		public string AppName
		{
			get { return AppNameCtrl.Text; }
			set { AppNameCtrl.Text = value; }
		}

		/// <summary>
		/// Нужно ли использовать авторизацию.
		/// </summary>
		public bool IsAutorization
		{
			get { return IsAutorizationCtrl.IsChecked == true; }
			set { IsAutorizationCtrl.IsChecked = value; }
		}

		/// <summary>
		/// <see cref="PlazaTrader.Address"/>.
		/// </summary>
		public EndPoint Address
		{
			get { return AddressCtrl.Text.To<EndPoint>(); }
			set { AddressCtrl.Text = value.ToString(); }
		}

		bool ITraderSettingsPanel.IsValid
		{
			get
			{
				if (Address == null)
					return false;

				if (IsAutorization)
				{
					if (Password.IsEmpty())
						return false;
				}

				return true;
			}
		}

		void ITraderSettingsPanel.Save(ITrader trader)
		{
			var plazaTrader = (PlazaTrader)trader;

			plazaTrader.Address = Address;

			if (IsAutorization)
			{
				plazaTrader.Login = Login;
				plazaTrader.Password = Password;
			}

			plazaTrader.AppName = AppName;

			plazaTrader.SyncTables(TablesCtrl.SelectedTables);
		}

		void ITraderSettingsPanel.Load(ITrader trader)
		{
			var plazaTrader = (PlazaTrader)trader;

			Login = plazaTrader.Login;
			Password = plazaTrader.Password;
			AppName = plazaTrader.AppName;
			Address = plazaTrader.Address;

			TablesCtrl.SelectedTables.Clear();
			TablesCtrl.SelectedTables.AddRange(plazaTrader.Tables.Select(t => t.Id));
		}
	}
}